<template>
  <div class="carousel-manage">
    <el-card class="box-card">
      <div slot="header" class="clearfix header-section">
        <div class="header-content">
          <div class="title-section">
            <el-icon class="title-icon"><Picture /></el-icon>
            <span class="title-text">轮播图管理</span>
          </div>
          <el-button type="primary" class="add-button" @click="addDialogVisible = true">
            <el-icon><Plus /></el-icon>
            添加轮播图
          </el-button>
        </div>
      </div>

      <el-form :inline="true" :model="searchForm" class="search-form" @submit.prevent>
        <el-form-item label="主题">
          <el-input
            v-model="searchForm.topic"
            placeholder="请输入主题"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="searchForm.title"
            placeholder="请输入备注"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" class="search-btn">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="resetSearch" class="reset-btn">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <el-table
        :data="carouselList"
        class="data-table"
        v-loading="loading"
        stripe
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="topic" label="主题" min-width="150" align="center" />
        <el-table-column prop="title" label="备注" min-width="200" align="center" />
        <el-table-column label="图片" width="120" align="center">
          <template #default="scope">
            <div class="image-container">
              <img :src="scope.row.image" alt="轮播图" class="carousel-img" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="editCarousel(scope.row)"
              class="action-btn edit-btn"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-popconfirm
              title="确定删除这个轮播图吗？"
              @confirm="deleteCarouselHandler(scope.row.id)"
              confirm-button-text="确定"
              cancel-button-text="取消"
            >
              <template #reference>
                <el-button
                  size="small"
                  type="danger"
                  class="action-btn delete-btn"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="pageNum"
        :page-sizes="[10, 20, 50, 100]"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        class="pagination"
      />

      <!-- 编辑对话框 -->
      <el-dialog
        v-model="editDialogVisible"
        title="编辑轮播图"
        width="500px"
        class="custom-dialog"
        :close-on-click-modal="false"
      >
        <el-form :model="editForm" ref="editFormRef" label-width="80px" :rules="rules">
          <el-form-item label="主题" prop="topic">
            <el-input v-model="editForm.topic" placeholder="请输入主题" />
          </el-form-item>
          <el-form-item label="备注" prop="title">
            <el-input v-model="editForm.title" placeholder="请输入备注" />
          </el-form-item>
          <el-form-item label="图片">
            <el-upload
              class="upload-demo"
              ref="editUploadRef"
              :action="'http://localhost:2000/lun/update'"
              :show-file-list="false"
              :auto-upload="false"
              :on-success="handleEditUploadSuccess"
              :before-upload="beforeUpload"
              :data="{ id: editForm.id, topic: editForm.topic, title: editForm.title }"
              name="image"
              :headers="uploadHeaders"
              :on-change="handleEditFileChange"
              :file-list="editFileList"
            >
              <el-button type="primary" class="upload-btn">
                <el-icon><Upload /></el-icon>
                更换图片
              </el-button>
            </el-upload>
            <div v-if="editForm.imageUrl || editForm.image" class="preview-img">
              <img
                :src="editForm.imageUrl ? editForm.imageUrl : editForm.image"
                alt="预览"
                class="preview-image"
              />
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="editDialogVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="submitEdit" class="save-btn">保存</el-button>
        </template>
      </el-dialog>

      <!-- 添加对话框 -->
      <el-dialog
        v-model="addDialogVisible"
        title="添加轮播图"
        width="500px"
        class="custom-dialog"
        :close-on-click-modal="false"
      >
        <el-form :model="addForm" ref="addFormRef" label-width="80px" :rules="rules">
          <el-form-item label="主题" prop="topic">
            <el-input v-model="addForm.topic" placeholder="请输入主题" />
          </el-form-item>
          <el-form-item label="备注" prop="title">
            <el-input v-model="addForm.title" placeholder="请输入备注" />
          </el-form-item>
          <el-form-item label="图片" prop="image">
            <el-upload
              class="upload-demo"
              ref="addUploadRef"
              action="http://localhost:2000/lun/add"
              :show-file-list="false"
              :auto-upload="false"
              :on-success="handleAddUploadSuccess"
              :before-upload="beforeUpload"
              :data="{ topic: addForm.topic, title: addForm.title }"
              name="image"
              :headers="uploadHeaders"
              :on-change="handleAddFileChange"
            >
              <el-button type="primary" class="upload-btn">
                <el-icon><Upload /></el-icon>
                选择图片
              </el-button>
            </el-upload>
            <div v-if="addForm.imageUrl" class="preview-img">
              <img :src="addForm.imageUrl" alt="预览" class="preview-image" />
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="addDialogVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="submitAdd" class="save-btn">提交</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Picture,
  Plus,
  Search,
  Refresh,
  Edit,
  Delete,
  Upload
} from '@element-plus/icons-vue'

import {deleteCarousel, getCarouselList, updateCarousel} from "@/request/carousel.js";

// 替换为二次封装


const formRef = ref()
const editFormRef = ref()
const searchForm = reactive({ topic: '', title: '' })
const rules = {
  topic: [{ required: true, message: '请输入主题', trigger: 'blur' }],
  title: [{ required: true, message: '请输入备注', trigger: 'blur' }],
}
const carouselList = ref([])
const loading = ref(false)
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const editDialogVisible = ref(false)
const editUploadRef = ref()
const editFileList = ref([])
const editForm = reactive({ id: '', topic: '', title: '', image: '', imageUrl: '', file: null })
const uploadHeaders = { }
const addDialogVisible = ref(false)
const addFormRef = ref()
const addUploadRef = ref()
const addForm = reactive({ topic: '', title: '', imageUrl: '', file: null })

function getImageUrl(fileName) {
  if (!fileName) return ''
  return `http://localhost:2000/${fileName}`
}

function fetchList() {
  loading.value = true
  getCarouselList({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    topic: searchForm.topic,
    title: searchForm.title
  })
    .then(res => {
      carouselList.value = res.data.records
      total.value = res.data.total
    })
    .finally(() => loading.value = false)
}

function handleUploadSuccess(res) {
  if (res.startsWith('添加成功')) {
    ElMessage.success('上传成功')
    fetchList()
    form.topic = ''
    form.title = ''
    form.imageUrl = ''
  } else {
    ElMessage.error(res)
  }
}

function beforeUpload(file) {
  const isImage = ["image/jpeg", "image/png", "image/gif"].includes(file.type)
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  return true
}

function handlePageChange(val) {
  pageNum.value = val
  fetchList()
}

function handleSizeChange(val) {
  pageSize.value = val
  pageNum.value = 1
  fetchList()
}

function handleSearch() {
  pageNum.value = 1
  fetchList()
}
function resetSearch() {
  searchForm.topic = ''
  searchForm.title = ''
  pageNum.value = 1
  fetchList()
}

function editCarousel(row) {
  editForm.id = row.id
  editForm.topic = row.topic
  editForm.title = row.title
  editForm.image = row.image
  editForm.imageUrl = ''
  editForm.file = null
  editFileList.value = []
  editDialogVisible.value = true
}

function handleEditUploadSuccess(res) {
  if (res === true || (typeof res === 'string' && res.startsWith('添加成功'))) {
    ElMessage.success('更新成功')
    editDialogVisible.value = false
    fetchList()
  } else {
    ElMessage.error('更新失败')
  }
}

function handleEditFileChange(file) {
  const reader = new FileReader()
  reader.onload = e => {
    editForm.imageUrl = e.target.result
  }
  reader.readAsDataURL(file.raw)
  editForm.file = file.raw
  // 保证 fileList 有文件
  editFileList.value = [file]
}

function submitEdit() {
  editFormRef.value.validate(valid => {
    if (!valid) return
    if (editForm.file) {
      // 更换了图片，手动上传（点击保存才上传）
      editUploadRef.value.submit()
    } else {
      // 没有更换图片，手动用 form-data 提交
      const formData = new FormData()
      formData.append('id', editForm.id)
      formData.append('topic', editForm.topic)
      formData.append('title', editForm.title)
      updateCarousel(formData).then(res => {
        if (res.data === true) {
          ElMessage.success('更新成功')
          editDialogVisible.value = false
          fetchList()
        } else {
          ElMessage.error('更新失败')
        }
      })
    }
  })
}

function deleteCarouselHandler(id) {
  deleteCarousel(id).then(res => {
    if (res.data === true) {
      ElMessage.success('删除成功')
      fetchList()
    } else {
      ElMessage.error('删除失败')
    }
  })
}

function handleAddFileChange(file) {
  // 预览图片
  const reader = new FileReader()
  reader.onload = e => {
    addForm.imageUrl = e.target.result
  }
  reader.readAsDataURL(file.raw)
  addForm.file = file.raw
}

function submitAdd() {
  addFormRef.value.validate(valid => {
    if (!valid) return
    if (!addForm.file) {
      ElMessage.error('请先选择图片')
      return
    }
    addUploadRef.value.submit()
  })
}

function handleAddUploadSuccess(res) {
  if (res.startsWith('添加成功')) {
    ElMessage.success('添加成功')
    addDialogVisible.value = false
    fetchList()
    addForm.topic = ''
    addForm.title = ''
    addForm.imageUrl = ''
    addForm.file = null
  } else {
    ElMessage.error(res)
  }
}

onMounted(() => {
  fetchList()
})
</script>

<style scoped>
.carousel-manage {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0;
  height: 100%;
  box-sizing: border-box;
}

.box-card {
  border-radius: 0;
  border: none;
  height: 100%;
  display: flex;
  flex-direction: column;
  box-shadow: none;
}

.header-section {
  background: #f5f7fa;
  color: #303133;
  padding: 16px 20px;
  margin: 0 0 20px 0;
  border-bottom: 1px solid #e4e7ed;
  flex-shrink: 0;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-icon {
  font-size: 20px;
  color: #409eff;
}

.title-text {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.add-button {
  background: #409eff;
  border: 1px solid #409eff;
  color: white;
  font-weight: 400;
  padding: 8px 16px;
  border-radius: 4px;
}

.add-button:hover {
  background: #66b1ff;
  border-color: #66b1ff;
}

.search-form {
  background: #fafafa;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
  border: 1px solid #e4e7ed;
  flex-shrink: 0;
}

.search-input {
  width: 200px;
}

.search-btn, .reset-btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-weight: 400;
}

.search-btn {
  background: #409eff;
  border: 1px solid #409eff;
  color: white;
}

.reset-btn {
  background: white;
  border: 1px solid #dcdfe6;
  color: #606266;
}

.data-table {
  width: 100%;
  margin: 0 auto;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
  flex: 1;
}

.data-table :deep(.el-table) {
  border: none;
  height: 100%;
}

.data-table :deep(.el-table__header) {
  background-color: #f5f7fa;
}

.data-table :deep(.el-table__header th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
  border-bottom: 1px solid #e4e7ed;
}

.data-table :deep(.el-table__body td) {
  border-bottom: 1px solid #f0f0f0;
}

.data-table :deep(.el-table__body tr:hover) {
  background-color: #f5f7fa;
}

.image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 8px;
}

.carousel-img {
  width: 80px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.action-btn {
  margin: 0 4px;
  padding: 6px 12px;
  border-radius: 4px;
  font-weight: 400;
}

.edit-btn {
  background: #409eff;
  border: 1px solid #409eff;
  color: white;
}

.delete-btn {
  background: #f56c6c;
  border: 1px solid #f56c6c;
  color: white;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 16px 0;
  flex-shrink: 0;
}

.custom-dialog {
  border-radius: 8px;
}

.upload-btn {
  background: #409eff;
  border: 1px solid #409eff;
  color: white;
  padding: 8px 16px;
  border-radius: 4px;
  font-weight: 400;
}

.preview-img {
  margin-top: 12px;
}

.preview-image {
  max-width: 120px;
  max-height: 80px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.cancel-btn {
  background: white;
  border: 1px solid #dcdfe6;
  color: #606266;
  padding: 8px 16px;
  border-radius: 4px;
}

.save-btn {
  background: #409eff;
  border: 1px solid #409eff;
  color: white;
  padding: 8px 16px;
  border-radius: 4px;
  font-weight: 400;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .carousel-manage {
    padding: 0;
  }

  .header-content {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  .search-input {
    width: 100%;
  }
}
</style>
